package com.yjy.workproject.filter;

import com.google.common.base.Strings;
import com.yjy.workproject.result.Result;
import com.yjy.workproject.util.JSONUtils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 设置允许跨域的过滤器
 */
@Component
public class CorsFilter implements Filter {

    private static final String OPTIONS = "OPTIONS";
    private static final String ZTSJ_TOKEN = "ZTSJ-TOKEN";
    private static final String ZTSJ_OPENID = "ZTSJ-OPENID";

    @Value("${exclude-url}")
    private String excludeUrl;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //给动态URL开放session
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        String url = request.getHeader("origin");
        response.addHeader("Access-Control-Allow-Origin", url);
        response.addHeader("Access-Control-Allow-Headers", "X-CSRF-Token,Content-Type");
        response.addHeader("Access-Control-Allow-Headers", "cache-control,X-Requested-With,ZTSJ-TOKEN,ZTSJ-OPENID");
        response.addHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS,PATCH");
        response.addHeader("Access-Control-Allow-Credentials", "true");
        response.addHeader("Access-Control-Expose-Headers", "ZTSJ-TOKEN");
        //非简单请求
        if (OPTIONS.equals(request.getMethod())) {  //EL Upload 请求校验
            response.setStatus(HttpServletResponse.SC_OK);
        }
       /* // 对token进行验证
        String token = request.getHeader(ZTSJ_TOKEN);
        String openId = request.getHeader(ZTSJ_OPENID);
        String path = request.getServletPath();

        if (!isExcludeUrl(path)) {
            token = Strings.isNullOrEmpty(token) ? request.getParameter(ZTSJ_TOKEN) : token;
            openId = Strings.isNullOrEmpty(openId) ? request.getParameter(ZTSJ_OPENID) : openId;
            //token为空
            if (Strings.isNullOrEmpty(token) || Strings.isNullOrEmpty(openId)) {
                // 过滤该请求，不对其进行路由
                writeMsg(response, ResultUtil.error(ResultEnum.TOKEN_1008));
                return ;
            }
            Integer userId = TokenUtil.unsign(token, Integer.class);
            //token过期
            if (userId == null) {
                // 过滤该请求，不对其进行路由
                writeMsg(response, ResultUtil.error(ResultEnum.ZTSJ_1005));
                return ;
            }
            String mdId = MD5Tools.md5(userId.toString());
            //非法请求
            if (!openId.equals(mdId)) {
                writeMsg(response, ResultUtil.error(ResultEnum.TOKEN_1009));
                return ;
            }
            //添加生成新的token信息
            AccessToken accessToken = TokenUtil.sign(userId.toString(), userId, 30 * 60);
            response.addHeader(ZTSJ_TOKEN, accessToken.getToken());
        }*/

        filterChain.doFilter(servletRequest, servletResponse);
    }

    private boolean isExcludeUrl(String path) {
        //得到多个URI
        //String urls = "/user/login";
        String urls = excludeUrl;
        String[] uris = urls.split(",");
        for (String uri : uris) {
            if (path.startsWith(uri)) {
                return true;
            }
        }
        return false;
    }

    private void writeMsg(HttpServletResponse response, Result<String> result) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.append(JSONUtils.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    }

    @Override
    public void destroy() {

    }
}
